import { cloneDeep } from 'lodash-es'

export const treeAddLevel = (data, level) => {
  data.forEach(function (item: any) {
    item.level = level + 1
    if (item.children && item.children.length > 0) {
      treeAddLevel(item.children, level + 1)
    }
  })
}

// 树结构数据添加线条结构
export const treeData = (data, isLast, hideLine, level, parentId) => {
  data.forEach((item, index) => {
    item.level = level + 1
    item.parentId = parentId
    if (index === 0) {
      item.isFirst = true
    } else {
      item.isFirst = false
    }
    if (index === data.length - 1) {
      item.isLast = true
    } else {
      item.isLast = false
    }
    item.hideLine = cloneDeep(hideLine)
    if (isLast) {
      item.hideLine.push(item.level - 1)
    }
    if (item.children && item.children.length > 0) {
      treeData(item.children, item.isLast, item.hideLine, level + 1, item.id)
    }
  })
}

// 通过当前选中节点找其所有祖先层级
export const getTreeNodeParents = (list, node) => {
  let arrRes = []
  const rev = (data, v) => {
    for (let i = 0; i < data.length; i++) {
      const item = data[i]
      if (item.id === v.parentId) {
        arrRes.unshift(item)
        rev(list, item)
        break
      } else {
        if (item.children.length > 0) {
          rev(item.children, v)
        }
      }
    }
    return arrRes
  }
  arrRes = rev(list, node)
  return arrRes
}

// 获取树结构数据中的指定数据
export const getActiveData = (data, v) => {
  let res = null
  const revert = (arr, id) => {
    arr.forEach((item: any) => {
      if (item.id === id) {
        res = item
      }
      if (item.children.length > 0) {
        revert(item.children, id)
      }
    })
  }
  revert(data, v)
  return res
}
